<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试上传文件</title>
    <style>
        .ball {
            width: 50px;
            height: 50px;
            background-color: red;
            border-radius: 50%;
            position: relative;
            animation: move 3s linear infinite;
        }

        @keyframes move {
            0% {
                left: 0;
            }

            50% {
                left: calc(100% - 50px);
            }

            100% {
                left: 0;
            }
        }
    </style>
</head>

<body>
    <div class="ball"></div>
    <form action="#" method="post" id="myForm">
        <div>
            <label for="inputFile">电影文件</label>
            <input type="file" id="inputFile" name="moviceFile">
        </div>
        <button type="submit">上传文件</button>
    </form>
    <div id="progress"></div>
</body>
<script>
    document.getElementById('myForm').addEventListener('submit', function (event) {
        event.preventDefault()
        const formData = new FormData(event.target)

        for (let [key, value] of formData.entries()) {
            console.log(key, value)
        }
        // fetch('/upload', {
        //     method: 'POST',
        //     body: formData
        // }).then(res => {
        //     console.log('res:', res)
        // })
    })

    document.getElementById('inputFile').addEventListener('change', async function (event) {
        const uploadFile = event.target.files[0]
        let result = {}
        try {
            result = await cutFile(uploadFile)
        } catch (error) {
            console.log('error:', error)
        }
        console.log('result:', result)
    })

    const CHUNK_SIZE = 1024 * 1024 * 5 // 5MB

    function cutFile(file) {
        return new Promise((resolve) => {
            const fileSize = file.size
            const chunkNum = Math.ceil(fileSize / CHUNK_SIZE)
            const chunks = []

            let worker = new Worker('worker.js', { type: 'module' })

            worker.postMessage({
                CHUNK_SIZE,
                file,
                chunkNum
            })

            let isUploading = false
            let currentChunkCount = 0
            worker.onmessage = function (event) {
                console.log('event:', event.data)
                switch (event.data.type) {
                    case 'progress':
                        // 设置上传进度
                        if (!isUploading) {
                            isUploading = true
                            requestAnimationFrame(() => {
                                document.getElementById('progress').innerText = event.data.content
                                isUploading = false
                            })
                        }

                        break
                    case 'fileInfo':
                        ++currentChunkCount;
                        chunks[event.data.content.index] = event.data.content;
                        if (currentChunkCount === chunkNum) {
                            // 确保最后一个分片的进度为 100%
                            requestAnimationFrame(() => {
                                document.getElementById('progress').innerText = '100.00%';
                            });
                            resolve(chunks);
                        } else {
                            // 使用 requestAnimationFrame 优化进度更新
                            if (!isUploading) {
                                isUploading = true;
                                requestAnimationFrame(() => {
                                    document.getElementById('progress').innerText = (currentChunkCount / chunkNum * 100).toFixed(2) + '%';
                                    isUploading = false;
                                });
                            }
                        }
                        break
                }

            }
        })

    }
</script>

</html>